<?php
/**
 * WeixinController 获取微信接口信息控制器
 * author hhz 2017.10.12
 */
namespace Api\Controller;

use Think\Controller;
use Common\Controller\WeixinController;

class TaskController extends Controller
{
    /*
     * 推送小程序消息
     */
    public function sendMessage()
    {
        set_time_limit(3600);
        $adId       = S('taskSendMessage');
        $form_model = M('UserFormid');
        echo $adId . '-';
        if ($adId > 0) {
            $ad_model = M('Ad');
            $info     = $ad_model->where(['ad_id' => $adId])->find();
            if (!$info) {
                S('taskSendMessage', null);
                S('taskSendMessageLast', null);
                echo 1;
                exit;
            } elseif ($info['status'] == 3) {
                //暂停
                echo 6;
                exit;
            } elseif ($info['status'] == 2) {
                S('taskSendMessage', null);
                S('taskSendMessageLast', null);
                $ad_model->where(['ad_id' => $adId])->save(['status' => 2, 'update_time' => time()]);
                echo 5;
                exit;
            } elseif ($info['status'] == 0) {
                $ad_model->where(['ad_id' => $adId])->save(['status' => 1, 'update_time' => time()]);
            } else {
                $ad_model->where(['ad_id' => $adId])->save(['update_time' => time()]);
            }
            //获取formid
            $start_time = strtotime('-7 day') - 3600;
            $where      = 'status = 0 and add_time > ' . $start_time;
            $lastid     = S('taskSendMessageLast');
            if ($lastid > 0) {
                $where = 'user_id > ' . $lastid . ' and ' . $where;
            }
            if ($info['end_time'] > 0) {
                $where .= ' and add_time < ' . $info['end_time'];
            }
            $list = $form_model
                ->where($where)
                ->limit(200)
                ->order('user_id asc')
                ->group('user_id')
                ->select();

            if (!$list) {
                //完成任务
                S('taskSendMessage', null);
                S('taskSendMessageLast', null);
                $ad_model->where(['ad_id' => $adId])->save(['status' => 2, 'update_time' => time()]);
                echo 2;
                exit;
            } else {
                //记录最后一个user_id
                $last = end($list);
                S('taskSendMessageLast', $last['user_id'], ['expire' => 86400]);
                //删除已取出的formid
                $ids   = array_column($list, 'id');
                $where = 'id in (' . implode(',', $ids) . ')';
                $form_model->where($where)->save(['status' => 1]);
                //发送消息
                $err      = [
                    '40037' => 'template_id不正确',
                    '41028' => 'form_id不正确，或者过期',
                    '41029' => 'form_id已被使用',
                    '41030' => 'page不正确',
                    '45009' => '接口调用超过限额',
                ];
                $suc_num  = 0;
                $err_code = '';
                foreach ($list as $v) {
                    $ret = $this->send($info, $v);
                    if (!isset($ret['errcode']) || $ret['errcode'] == 0) {
                        $suc_num++;
                    } else {
                        $err_code = $ret['errcode'];
                        if (isset($err[$err_code])) {
                            $err_code .= $err[$ret['errcode']];
                        }
                        $form_model->where(['id' => $v['id']])->save(['err_code' => $err_code]);
                    }
                }
                //更新任务信息
                $ad_model->where(['ad_id' => $adId])->setInc('success_num', $suc_num);
                $ad_model->where(['ad_id' => $adId])->setInc('send_num', count($list));
                if ($err_code) {
                    $ad_model->where(['ad_id' => $adId])->save(['err_code' => $err_code]);
                }
                echo 3;
                exit;
            }
        } else {
            //清理过期的formid，每天清理一次
            $cacheKey = 'clearFormID' . date('Ymd');
            if (!S($cacheKey)) {
                S($cacheKey, 1, ['expire' => 86400]);
                $time  = strtotime('-7 day');
                $where = 'add_time <' . $time;
                $form_model->where($where)->delete();
            }
        }

        echo 4;
        exit;
    }

    private function send($data = [], $user = [])
    {
        $tplData = [
            'keyword1' => [
                'value' => $data['content'],
                'color' => '#FB1322',
            ],
            'keyword2' => [
                'value' => $data['ad_name'],
                'color' => '#173177',
            ],
            'keyword3' => [
                'value' => $data['tip_message'],
                'color' => '#173177',
            ]
        ];
        $param   = [
            'touser'           => $user['openid'],
            'template_id'      => C('news_tpl_send'),
            'page'             => '/pages/index/index',
            'form_id'          => $user['form_id'],
            'data'             => $tplData,
            "emphasis_keyword" => "keyword1.DATA"
        ];
        $t       = WeixinController::instance()->send_template($param);

        return $t;
    }

    public function dumpCache()
    {

        echo 'login-' . S('cacheLoginControllerDologin') . '  ';
        echo 'wd-' . S('WithdrawalsControllerCash');

        exit;
    }
}